﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VkClientIM.Logic;
using VkClientIM.Windows;
using Vkontakte.Api;
using Vkontakte.Api.Operations;
using AudioRecord = Vkontakte.Api.AudioRecord;

namespace VkClientIM
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : UserControl
	{
		private Session _attachedSession = null;

		public MainWindow()
		{
			InitializeComponent();

		}

		#region Взаимодействие с пользователем

		private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
		{
			var str = (string)((Thumb)sender).Tag;

			if (str.Contains("T"))
			{
				this.Height = Math.Min(Math.Max(this.MinHeight, this.ActualHeight - e.VerticalChange), this.MaxHeight);
				Canvas.SetTop(this, Canvas.GetTop(this) - this.Height + this.ActualHeight);
			}
			if (str.Contains("L"))
			{
				this.Width = Math.Min(Math.Max(this.MinWidth, this.ActualWidth - e.HorizontalChange), this.MaxWidth);
				Canvas.SetLeft(this, Canvas.GetLeft(this) - this.Width + this.ActualWidth);
			}
			if (str.Contains("B"))
			{
				this.Height = Math.Min(Math.Max(this.MinHeight, this.ActualHeight + e.VerticalChange), this.MaxHeight);
			}
			if (str.Contains("R"))
			{
				this.Width = Math.Min(Math.Max(this.MinWidth, this.ActualWidth + e.HorizontalChange), this.MaxWidth);
			}
			e.Handled = true;
		}


		private Window FindRoot()
		{
			FrameworkElement element = this;
			while (!(element is Window))
			{
				element = element.Parent as FrameworkElement;
			}
			Window ret = element as Window;
			return ret;
		}

		private void ToggleButton_Checked(object sender, RoutedEventArgs e)
		{
			FindRoot().Topmost = true;
		}

		private void ToggleButton_Unchecked(object sender, RoutedEventArgs e)
		{
			FindRoot().Topmost = false;
		}
		#endregion

		#region Закрытие
		private void TaskbarExit(object sender, RoutedEventArgs e)
		{
			AllowClose = true;
			if (App.Current.ApiLogic != null)
			{
				App.Current.ApiLogic.Close();
			}
			App.Current.ApiLogic = null;
			FindRoot().Close();
		}

		internal bool AllowClose { get; private set; }
		#endregion

		public void AttachSession(Session s)
		{
			_attachedSession = s;
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			new ConversationWindow().Show();
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			if (_attachedSession==null)
			{
			a:
				var authenticationWindow = new AuthenticationWindow();
				if (authenticationWindow.ShowDialog() != true)
				{
					if (MessageBox.Show("Авторизация не пройдена\nПопробовать ещё раз", "Ошибка", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
					{
						goto a;
					}
					else
					{
						App.Current.RestoreIEProxySettings();
						App.Current.Shutdown(0);
					}
				}
				else
				{
					BringIntoView();
					Focus();
					_attachedSession = authenticationWindow.authorizator.GetAuthorizationToken();
				}
			}
			App.Current.RestoreIEProxySettings();
			if (_attachedSession != null)
			{
				Authenticated(_attachedSession);
			}
		}


		private void Authenticated(Session apiSession)
		{
			App.Current.ApiClient = new ApiClient( AuthenticationWindow.MyAppID, apiSession );

			var audioGet = new AudioGet();
			audioGet.Completed += delegate
				{
					AudioRecord[] records= audioGet.GetResult();
					
					for (int i=0;i<records.Length;i++)
					{
						var audiorecord = new Logic.AudioRecord();
						audiorecord.Url = new Uri( records[ i ].Url );
						audiorecord.Artist = records[ i ].Artist;
						audiorecord.Name = records[ i ].Title;
						audiorecord.Duration = records[i].Duration;
						audioPlayer.Dispatcher.Invoke(
							new Action<Logic.AudioRecord>( audioPlayer.Playlist.AddAudioRecord ),
							audiorecord );
					}
				};
			App.Current.ApiClient.ExecuteQuerry( audioGet );

			var videoGet = new VideoGet();
			videoGet.Completed += delegate
			{

			};

			App.Current.ApiClient.ExecuteQuerry(videoGet);


			App.Current.ApiLogic = new ApiLogic(App.Current.ApiClient);
			App.Current.ApiLogic.AttachPlacesCache(App.Current.ClientDatabase);
			App.Current.ApiLogic.Start();
			profile.DataContext = App.Current.ApiLogic.MyProfile;

			contacts.DataContext =
				App.Current.ApiLogic.ContactList.VisibleContactList;
			
		}

		private void RadioButton_Checked(object sender, RoutedEventArgs e)
		{
			RadioButton radioButton = sender as RadioButton;
			if (this.IsInitialized)
			{
				string set = (string)radioButton.Tag;
				switch (set)
				{
					case "0":
						contacts.Visibility = Visibility.Visible;
						audioPlayer.Visibility = Visibility.Hidden;
						settings.Visibility = Visibility.Hidden;
						
						break;
					case "1":
						contacts.Visibility = Visibility.Hidden;
						audioPlayer.Visibility = Visibility.Visible;
						settings.Visibility = Visibility.Hidden;
						
						break;
					case "2":
						contacts.Visibility = Visibility.Hidden;
						audioPlayer.Visibility = Visibility.Hidden;
						settings.Visibility = Visibility.Visible;
						
						break;
				}
			}
		}

	}
}
